package ch.usi.inf.pf2.analyzer;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @author Thomas Mantegazzi, Yotam Sharon
 * @date 20 april 2010
 *
 */

/**
 * The TokenRecognizer can recognize the given regex in a String text in a given
 * position.
 */

public class TokenRecognizer {

	private TokenType tokenType;
	private Matcher matcher;
	private Pattern pattern;
	private int currentPosition;

	public TokenRecognizer(TokenType tokenType, final String regex) {
		this.tokenType = tokenType;
		this.pattern = Pattern.compile(regex);
	}

	public void setText(String text) {
		matcher = pattern.matcher(text);
	}

	public boolean find(final int currentPosition) {
		this.currentPosition = currentPosition;
		if (matcher.find(currentPosition)) {
			final int start = matcher.start();
			if (currentPosition == start) {
				return true;
			}
		}
		return false;
	}

	public Token getToken() {
		final String text = matcher.group();
		Token matchedToken = new Token(text, currentPosition, tokenType);
		return matchedToken;
	}

	public int getTokenLength() {
		final String match = matcher.group();
		return match.length();
	}

}
